<?php

namespace App\Console;

use App\Models\Order;
use Illuminate\Support\Facades\Log;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use DB;
use Illuminate\Support\Carbon;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
           $timestamp = now()->timestamp;
            /* Order::query()->whereNotNull('freeze_expired_at')->where('freeze_expired_at', '<=', $timestamp)
                ->chunk(100, function ($orders) {
                    foreach ($orders as $order) {
                        \product_storehouse_order_free_up($order->id);
                    }
                });*/
                //一天前的订单自动发货
                $timestamp=$timestamp-24*60*60;
                  Order::query()->whereNotNull('date')->where('date', '<=', $timestamp)->where('delivery_status',  "pending")
                ->chunk(100, function ($orders) {
                    foreach ($orders as $order) {
                         $order->delivery_viewed = '0';
                         $order->delivery_status = "confirmed";
                         $order->save();
                         Log::channel('single')->info("{$order->id}订单自动发货");
                    }
                });
                $timestamp=$timestamp-6*24*60*60;
                //七天前的订单已发货自动确认收货
                Order::query()->whereNotNull('freeze_expired_at')->whereNotNull('date')->where('date', '<=', $timestamp)->where('delivery_status',  "confirmed")
                // Order::query()->whereNotNull('freeze_expired_at')->whereNotNull('date')->where('date', '<=', $timestamp)->where('delivery_status',  "delivered")//历史记录处理
                ->chunk(100, function ($orders) {
                    foreach ($orders as $order) {
                        $result=product_storehouse_order_free_up($order->id);
                        Log::channel('single')->info(now()->timestamp."释放订单 {$order->id} $result");
                        if($result===true){
                             $order->delivery_viewed = '0';
                             $order->delivery_status = "delivered";
                             $order->save();
                            
                            foreach ($order->orderDetails as $key => $orderDetail) {
                                $orderDetail->delivery_status = "delivered";
                                $orderDetail->save();
                            }
                             Log::channel('single')->info("{$order->id}订单自动确认收货");
                        }
                       
                    }
                });
                 
                //Log::channel('single')->info(now()->timestamp);
        })->everyMinute();
        
        $schedule->call(function () {

              Order::query()->whereNotNull('seller_id')->where('product_storehouse_total', '>', 0)->where('product_storehouse_status', 0)
            ->chunk(300, function ($orders) {
                
                foreach ($orders as $order) {
                     //DB::beginTransaction();
                    $shop = $order->shop;
                    if($shop && $shop->user){
                        $user = $shop->user;
            
                        if ($user->balance >= $order->product_storehouse_total) {
                            $user->balance -= $order->product_storehouse_total;
                            $user->save();
                
                            $shop->admin_to_pay += $order->grand_total;
                            $shop->save();
                
                
                            // 保存订单冻结资金过期时间
                            $freezeDays = get_setting('frozen_funds_unfrozen_days', 15);
                            $order->freeze_expired_at = Carbon::now()->addDays($freezeDays)->timestamp;
                
                            $order->product_storehouse_status = 1;
                            $order->save();
                
                           // DB::commit();
                             Log::channel('single')->info("{$order->id}订单卖家自动处理成功");
                        }else{
                             //DB::rollBack();
                            //Log::channel('single')->info("{$order->id}订单卖家自动处理失败余额不足");
                        }
                    }
                    
                    
                    
                }
                
            });
             
            //Log::channel('single')->info("卖家自动处理订单");
        })->everyMinute();
    }
/*
商家可用余额充足的情况下自动处理新订单
$ord商家可用余额充足的情况下自动处理新订单er = Order::findOrFail($orderId);
//        dd($order);
        if (!$order || $order->product_storehouse_total <= 0) return response()->json(['success' => 0, 'message' => translate('Something went wrong!')]);
        if ($order->product_storehouse_status == 1) return response()->json(['success' => 0, 'message' => translate('Payment completed')]);

        DB::beginTransaction();
        $shop = $order->shop;
        $user = $shop->user;

        if ($user->balance >= $order->product_storehouse_total) {
            $user->balance -= $order->product_storehouse_total;
            $user->save();

            $shop->admin_to_pay += $order->grand_total;
            $shop->save();


            // 保存订单冻结资金过期时间
            $freezeDays = get_setting('frozen_funds_unfrozen_days', 15);
            $order->freeze_expired_at = Carbon::now()->addDays($freezeDays)->timestamp;

            $order->product_storehouse_status = 1;
            $order->save();

            DB::commit();
            return response()->json(['success' => 1, 'message' => translate('Payment completed')]);
        }
        DB::rollBack();
        return response()->json(['success' => 0, 'message' => translate('Insufficient balance')]);
*/
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}
